<template>
  <el-config-provider :locale="locale" :size="size">
    <router-view />
  </el-config-provider>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, watchEffect } from 'vue'
import { RouterView } from 'vue-router'
import { useTitle } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import { messages } from '@/i18n'
import { handleThemeStyle } from '@/utils/theme'
import { useAppStore } from '@/store/modules/app'
import ws from '@/utils/gps/webSocket'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
import { ElNotification, ElMessageBox } from 'element-plus'
import { gpsbus, rtcbus } from '@/utils/gps/event'
import Layout from "@/layout/index.vue"

const appStore = useAppStore()
const { t } = useI18n()
const locale = computed(() => messages[appStore.language].el)
const size = computed(() => appStore.componentSize)

// 设置标题
useTitle(t('app.title'))

onMounted(() => {
  nextTick(() => {
    // 初始化主题样式
    handleThemeStyle(appStore.theme)
  })
})
onUnmounted(() => {
  ws.closeWebSocket()
})
watchEffect(() => {
  if (userStore?.user.username) {
    nextTick(() => {
      console.log('2', userStore.user.username)
      if (userStore.user.username) {
        initWebsocket(userStore.user.username)
      }
    })
  }
})

const initWebsocket = (username: string) => {
  //   const testWs = 'wss://gps.teredy.com'
  // const testWs = 'wss://gps.1688wxq.com'
  // const testWs = 'ws://127.0.0.1:8085'
  // const testWs = 'ws://192.168.1.112:8085'
  const h = import.meta.env.VITE_API_URL
  let host = h.replace(/(http:\/\/|https:\/\/)/, '')
  if (h.startsWith('http://')) {
    host = 'ws://' + host
  } else {
    host = 'wss://' + host
  }
  const testWs = host
  console.log('3', testWs)
  var prot = 'ws:'
  if (window.location.protocol === 'https:') {
    prot = 'wss:'
  }
  const wsHost = process.env.NODE_ENV === 'production' ? prot + '//' + window.location.host : testWs
  ws.initWebSocket(wsHost + '/websocket', username, userStore.token, handleWsCallback)
}

const handleWsCallback = (orgdata: string) => {
  if (orgdata == 'otherLogin') {
    showDialog('事件通知', '有人在其它地方登录')
    return
  }
  if (orgdata == 'userModifyed') {
    showDialog('事件通知', '有人修改了用户信息')
    return
  }
  if (orgdata == 'newFriend') {
    showDialog('事件通知', '好友同意')
    return
  }
  if (orgdata.substring(0, 7) === 'newMsg:') {
    let str = orgdata.substring(7)
    showDialog('事件通知', str + '想添加你为好友')
    return
  }
  if (orgdata.substring(0, 5) === 'kefu:') {
    let str = orgdata.substring(5)
    showDialog('事件通知', '新客服消息:' + str)
    return
  }
  if (orgdata.substring(0, 7) === 'webrtc:') {
    let jstr = orgdata.substring(7)
    let rtc = JSON.parse(jstr)
    if ('invite' === rtc.type) {
      gpsbus.emit('RTC_INVITE', rtc)
      return
    } else if ('cancel' === rtc.type) {
      gpsbus.emit('RTC_CANCEL', rtc)
      return
    }
    rtcbus.emit(rtc.type, rtc.data)
    return
  }
  const resp = JSON.parse(orgdata)
  var action = resp.messageType
  if (action === 'TYPE_EVENTS') {
    var data = resp.event
    gpsbus.emit('WS_CMD_EVENTS', resp)
    if (data.type === 'alarm') {
      if (data.attributes.alarm === 'sos') {
        ElMessageBox.alert(data.imei + '发生SOS报警', {
          confirmButtonText: '确定'
        })
        return
      } else {
        showDialog('报警', data.imei + ':' + data.attributes.alarm, 'warning')
        //   position: 'bottom-right',
        //   duration: 0
        return
      }
    }
    // communicate.emit('remindmsg', data);
    showDialog('事件通知', data.imei + ':' + data.type)
  } else if (action === 'TYPE_RESULTS') {
    let data = resp.commandResult
    // this.$Message.success('Command:' + data.result + ' ' + data.reason)
    if (data.result) {
      var res = '成功'
      if (data.resultObject) {
        // var j = JSON.parse(data.resultObject)
        var j = JSON.stringify(data.resultObject)
        res += '\n'
        res += j
      }
      showDialog('命令发送结果', res)
    } else {
      showDialog('命令发送失败', '原因：' + data.reason)
    }
    gpsbus.emit('WS_CMD_RESULT', resp)
  } else if (action === 'TYPE_POSITIONS') {
    gpsbus.emit('WS_CMD_POSITIONS', resp)
  } else if (action === 'TYPE_TXT_MSG') {
    var data1 = resp.txtMsg
    showDialog('收到消息提示', resp.imei + ':' + data1, 'warning')
    // showDialog({
    //   title: '收到消息提示',
    //   message: '' + data,
    // })
  }
}
const showDialog = (title: string, message: string, type?: string) => {
  // ElNotification({
  //   title: title,
  //   message: message,
  //   type: 'warning'
  // })
}
</script>
